package cn.itcast.service;

import cn.itcast.dao.CheckGroupDao;
import cn.itcast.entity.PageResult;
import cn.itcast.pojo.CheckGroup;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 *Author:TH
 *Dete:2019/10/2019:51
 */
@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    //添加检查组
    public void add(CheckGroup checkGroup,Integer[] checkitemIds) {
        checkGroupDao.add(checkGroup);

        //添加检查组与检查项关联
        addCheckGroupAndCheckItems(checkGroup.getId(),checkitemIds);

    }

    //添加检查组与检查项关联
    public void addCheckGroupAndCheckItems(Integer checkGroupId,Integer[] checkitemIds){
        if (checkitemIds!=null&&checkitemIds.length>0){
            for (Integer checkitemId : checkitemIds) {
                Map<String,Integer> map = new HashMap<String,Integer>();
                map.put("checkgroup_id",checkGroupId);
                map.put("checkitem_id",checkitemId);
                checkGroupDao.addCheckGroupAndCheckItems(map);
            }
        }
    }
    
    //分页查询
    public PageResult pageQuery(Integer cp, Integer ps, String qs) {
        PageHelper.startPage(cp,ps);
        Page<CheckGroup> page = checkGroupDao.findByCondition(qs);
        return new PageResult(page.getTotal(),page.getResult());
    }

    //按照id删除
    public void delectById(Integer id) {
    }

    //按照id查询
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }


    public void edit(CheckGroup checkGroup,Integer[] checkitemIds) {
        //删除检查组所有的检查项
        checkGroupDao.deleteAssociation(checkGroup.getId());
        //建立新的检查组与检查相关系
        addCheckGroupAndCheckItems(checkGroup.getId(),checkitemIds);
        //更新检查组信息
        checkGroupDao.edit(checkGroup);
    }


    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
        return checkGroupDao.findCheckItemIdsByCheckGroupId(id);
    }


}
